package tpf.designer.pattern.course10.homework.exercise2;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SelfQueue {
    int max = 5;
    LinkedList<Integer> ProdLine = new LinkedList<>();
    Lock lock = new ReentrantLock();
    Condition full = lock.newCondition();
    Condition empty = lock.newCondition();

    /**
     * 生产
     * @param ProdRandom
     */
    public void produce(int ProdRandom){
        try {
            lock.lock();
            while(max == ProdLine.size()){
                System.out.println("存储量达到上限，请等待");
                full.await();
            }
            ProdLine.add(ProdRandom);
            empty.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
            lock.unlock();
        }
    }

    /**
     * 消费
     * @return
     */
    public int consume(){
        int m = 0;
        try {
            lock.lock();
            while(ProdLine.size() == 0){
                System.out.println("队列是空的，请稍候");
                empty.await();
            }
            m = ProdLine.removeFirst();
            full.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
            lock.unlock();
            return m;
        }
    }
}
